var fs = require('fs')
var request = require('request')
var config = require('../../config.json')
var seeker = require('../seeker')
var muilter = require('../../multerUtil')
var upload = muilter.single('file')
var $ = require('../util')
var cookie = $.cookie || ''

module.exports = function (router) {
  router.all('/service/:app/*', upload, function (req, res, next) {
    if (!config.remote_data) {
      return next()
    }
    var host = config.remote_host
    var data = req.body
    var reqPath = req.path
    var type = req.get('Content-Type')
    var opts = {
      method: 'get',
      url: host + req.path,
      query: req.query,
      headers: {
        'Content-Type': req.get('Content-Type'),
        'content-length': req.get('Content-length'),
        'Set-Cookie': $.cookie,
        'Cookie': $.cookie
      }
    }
    if (data) {
      if (type) {
        if (type.indexOf('form') >= 0) {
          opts.formData = JSON.parse(JSON.stringify(data))
        } else if (type.indexOf('json') >= 0) {
          opts.body = data
          opts.json = true
        }
      } else {
        opts.body = data
        opts.json = true
      }
    }
    if (req.query) {
      var f = ''
      for (let i in req.query) {
        f += i + '=' + req.query[i] + '&'
      }
      if (f !== '') {
        f = f.slice(0, -1)
        opts.url += '?' + f
      }
    }
    if (config.request_body_out) {
      console.log(req.body)
    }

    if (opts.formData && req.file) {
      // opts = getUploadRequest(req, opts)
      return sendFile(opts.url, req, res)
    }
    // console.log(opts)
    var reqify = request(opts, function (error, response, body) {
      var ext = ''
      if (config.seeker_open) {
        ext = seeker(reqPath, req, body) || null
        if (ext) {
          ext += '.json'
        }else {
          ext = ''
        }
      }
      if (error) {
        console.error('TRANSMIT ERROR: '.red + error)
      } else {
        console.log('TRANSMIT DONE: '.green + opts.url + ' ' + ext.gray.underline)
      }
      if (response && response.caseless && response.caseless.dict['set-cookie']) {
        $.cookie = response.caseless.dict['set-cookie'][0]
      }

      return res.send(body)
    })
    if (config.request_log) {
      $.writeFile(reqify, 'log/Reuqeset' + reqPath.replace(/\//g, '.'))
    }
  })
}

// 旧版上传逻辑
function getUploadRequest (req, opts) {
  opts.formData[req.file.fieldname] = fs.createReadStream(req.file.path)
  if (opts.formData) {
    opts = {
      formData: opts.formData,
      url: opts.url,
      headers: {
        'Content-Type': req.get('Content-Type'),
        'Set-Cookie': $.cookie,
        'Cookie': $.cookie
      }
    }
  }
  return opts
}

function sendFile (url, req, res) {
  console.log(config.remote_host + url)
  var r = request.post(url, (err, resp, body) => {
    err && console.log(err)
    res.send(body)
  })
  r.setHeader('Set-Cookie', $.cookie)
  r.setHeader('Cookie', $.cookie)
  var form = r.form()
  if (req.file) {
    form.append('file', fs.createReadStream(process.cwd() + '/' + req.file.path))
  }
}
